package org.vacoor.xqq.hotkey.impl.linux;

import jxgrabkey.JXGrabKey;
import org.vacoor.xqq.hotkey.Demo;
import org.vacoor.xqq.hotkey.OSHotKeyBinder;
import org.vacoor.xqq.hotkey.OSHotKeyManager;
import org.vacoor.xqq.util.OS;

import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Linux 平台系统级热键, 对JXGrabKey简单封装
 * JXGrabKey:
 * http://sourceforge.net/projects/jxgrabkey/files/jxgrabkey/
 * <p/>
 * <p/>
 * User: Vacoor
 */
public class JXGrabKeyManager extends OSHotKeyManager {
    private static final String LINUX_64_LIB = "lib/native_lib/JXGrabKey_amd64.so";
    private static final String LINUX_32_LIB = "lib/native_lib/JXGrabKey_i386.so";

    private static ConcurrentHashMap<Integer, OSHotKeyBinder> binders = new ConcurrentHashMap<Integer, OSHotKeyBinder>();
    private static JXGrabKey jxGrabKey;
    private static boolean initialzed;

    private static void init() {
        if (!initialzed && OS.isLinux()) {
            try {
                String lib;
                if (OS.is64Arch()) {
                    lib = getResource(LINUX_64_LIB).getPath();
                } else {
                    lib = getResource(LINUX_32_LIB).getPath();
                }
                System.load(lib);
                jxGrabKey = JXGrabKey.getInstance();
            } catch (Throwable t) {
            }
        }
        initialzed = true;
    }

    static URL getResource(String path) {
        return Demo.class.getClassLoader().getResource(path);
    }

    @Override
    public boolean supportCurrentOS() {
        if (!initialzed) {
            init();
        }
        return jxGrabKey != null;
    }

    @Override
    public OSHotKeyBinder getOSHotKeyBinder(int identifier) {
        if (!supportCurrentOS()) {
            return null;
        }
        OSHotKeyBinder binder = binders.get(identifier);
        if (binder != null) {
            return binder;
        }
        synchronized (binders) {
            if (binder == null) {
                binder = new JXGrabKeyBinder(jxGrabKey, identifier);
                binders.put(identifier, binder);
            }
        }
        return binder;
    }

    @Override
    public void destory() {
        if (jxGrabKey != null) {
            /*
            for(int identifier : binders.keySet()) {
                jxGrabKey.unregisterHotKey(identifier);
            }
            */
            jxGrabKey.cleanUp();
        }
    }

}
